package com.example.service;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.ResultBody;
import com.example.config.JwtUtil;
import com.example.config.security.LoginUser;
import com.example.dao.UserMapper;
import com.example.entity.User;
import com.example.entity.dto.DtoUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
   @Resource
    private UserMapper userMapper;
   @Autowired
   @Qualifier("redis1")
   private RedisTemplate redisTemplate;
   @Autowired
   private AuthenticationManager AuthenticationManager;


    @Override
    public List<DtoUser> queryRole(String username) {
        return null;
    }

    @Override
    public ResultBody<Map<String, Object>> login(User user) {
        UsernamePasswordAuthenticationToken authorization =
                new UsernamePasswordAuthenticationToken(user.getUsername(),user.getPassword());
        Authentication authenticate = AuthenticationManager.authenticate(authorization);
        if(Objects.isNull(authenticate)){
            throw new RuntimeException("认证失败");
        }
        LoginUser loginUser =(LoginUser) authenticate.getPrincipal();
        String token = JwtUtil.getToken(loginUser.getUser().getId(), loginUser.getUsername());
        String id = loginUser.getUser().getId();
        Collection<? extends GrantedAuthority> authorities = loginUser.getAuthorities();
        redisTemplate.opsForValue().set(id,authorities);
        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("id",id);
        return new ResultBody<>(true,map,"用户登录成功");
    }
    @Override
    public ResultBody logout(HttpServletRequest request) {
        UsernamePasswordAuthenticationToken authentication =(UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        String principal =(String) authentication.getPrincipal();
        Boolean logout = redisTemplate.delete(principal);
        if(logout){
            return new ResultBody(logout,null,"退出成功");
        }else {
            return new ResultBody(logout,null,"退出失败");
        }
    }
}
